const connection = require('../app/database')

class CommentService {
  async publishComment(userId, momentId, content) {
    const statement = `INSERT INTO comment (content, moment_id, user_id) VALUES(?, ?, ?);`
    const [result] = await connection.execute(statement, [content, momentId, userId])
    return result
  }
  async updateComment(commentId, content){
    const statement = `UPDATE comment SET content = ? WHERE id = ?;`
    const [result] = await connection.execute(statement, [content, commentId])
    return result
  }
  async deleteComment(commentId){
    const statement = `DELETE FROM comment WHERE id = ?;`
    const [result] = await connection.execute(statement, [commentId])
    return result
  }
  async replyComment(commentId, userId, momentId, content){
    const statement = `INSERT INTO comment (content, moment_id, user_id, comment_id) VALUES(?, ?, ?, ?);`
    const [result] = await connection.execute(statement, [content, momentId, userId, commentId])
    return result
  }
  async getCommentListByMomentId(momentId){
    const statement = `SELECT c.id, c.content, c.comment_id commendId, c.createAt createTime,
    JSON_OBJECT('id', u.id, 'name', u.name) user
    from comment c
    LEFT JOIN user u
    on c.user_id = u.id
    where c.moment_id = ?;`
    const [result] = await connection.execute(statement, [momentId])
    return result
  }
}

module.exports = new CommentService()